#include "Board.h"

static Board* instance = NULL;
static bool button_pushed = false;

Board* Board::get_instance()
{
	if(instance == NULL)
	{
		instance = new Board();
	}
	return instance;
}

Board::Board() : Window(Point(100, 100), 800, 800, "Fox and Hounds")
{
	square_width = x_max() / 8;
	square_height = y_max() / 8;
	draw_board();
	for(int r = 0; r < 8; r++)
	{
		positions.push_back(vector<Player_type>());
		for(int c = 0; c < 8; c++)
		{
			positions[r].push_back(none);
		}
	}
	positions[0][1] = opponent;
	positions[0][3] = opponent;
	positions[0][5] = opponent;
	positions[0][7] = opponent;
}

Board::Board(Point xy, int w, int h, const string& title ): Window(xy,w,h,title)
{
}

void Board::draw_board()
{
	// Add buttons
	for(int r = 0; r < 8; ++r)
	{
		for(int c = 0; c < 8; ++c)
		{
			if((r + c) % 2 == 1)
			{
				std::stringstream stream;
				stream << "(" << c << ", " << r << ")";
				Button* button = new Button(Point(square_width * r, square_height * c), square_width, square_height, stream.str(), cb_next);
				Rectangle* rect = new Rectangle(Point(square_width * r, square_height * c), square_width, square_height);
				rect->set_fill_color(fl_rgb_color(0, 55, 0));
				attach(*button);
				attach(*rect);
			}
			else
			{
				Rectangle* rect = new Rectangle(Point(square_width * r, square_height * c), square_width, square_height);
				rect->set_fill_color(fl_rgb_color(0, 99, 0));
				attach(*rect);
			}
		}
	}
}

void Board::wait_for_button()
{
	while (!button_pushed) Fl::wait();
	button_pushed = false;
	Fl::redraw();
}

void Board::cb_next(Address button_address, Address window_address) // callback for next_button
{
	Fl_Widget* theWidget = static_cast<Fl_Widget*>(button_address);
	int c = theWidget->x() / theWidget->w();
	int r = theWidget->y() / theWidget->h();
	Player* p = Game::get_instance()->the_player;
	if(p->is_legal_move(make_pair(r, c)))
	{
		if(!p->first_move)
		{
			p->move_to_position(make_pair(r, c));
		}
		button_pushed = true;
	}
}

bool Board::is_occupied(pair<int, int> position)
{
	bool ret = Board::get_instance()->positions[position.first][position.second] != none;
	return ret;
}